package com.soso.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.soso.dao.RolesDao;
import com.soso.dao.Userroles;
import com.soso.dao.UsersDao;
import com.soso.entity.Roles;
import com.soso.entity.UserSearch;

import com.soso.entity.Users;
import com.soso.impl.UsersImpl;
import com.soso.service.UsersService;
import com.soso.util.UUIDutils;

@Controller
public class UsersController {

	@Autowired
	private UsersImpl usersimpl;
	@Autowired
	private UsersDao userdao;
	@Autowired
	private RolesDao rolesdao;
	@Autowired
	private Userroles userrolesdao;

	// 查询全部
	@ResponseBody
	@CrossOrigin(origins = "*")
	@RequestMapping("/getall")
	public Map<String, Object> getall(UserSearch st, Integer page, Integer limit) {

		Specification<Users> spe = getspe(st);
		Map<String, Object> map = new HashMap<String, Object>();
		Pageable p = PageRequest.of(page - 1, limit);
		Page<Users> s = userdao.findAll(spe, p);
		List<Users> list = s.getContent();

		long count = s.getTotalElements();

		if (list != null) {
			map.put("code", "0");
			map.put("msg", "true");
			map.put("count", count);
			map.put("data", list);
		} else {
			map.put("code", "1");
			map.put("msg", "false");

		}
		return map;
	}

	private Specification<Users> getspe(UserSearch st) {

		return new Specification<Users>() {

			public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate p = criteriaBuilder.conjunction();// 动态表达式
				List<Expression<Boolean>> list = p.getExpressions();// 动态sql表达式集合
				SimpleDateFormat sim = new SimpleDateFormat("yyyy-MMMM-dd");
				if (!StringUtils.isEmpty(st.getLoginName())) {

					list.add(criteriaBuilder.like(root.<String>get("LoginName"), "%" + st.getLoginName() + "%"));
				}

				if (!StringUtils.isEmpty(st.getIsLockout())) {

					list.add(criteriaBuilder.like(root.get("IsLockout"), "%" + st.getIsLockout() + "%"));
				}
				if (!StringUtils.isEmpty(st.getBegincreateTime())) {

					list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("CreateTime"), st.getBegincreateTime()));

				}
				if (!StringUtils.isEmpty(st.getEndcreateTime())) {

					list.add(criteriaBuilder.lessThanOrEqualTo(root.get("CreateTime"), st.getEndcreateTime()));
				}

				if (!StringUtils.isEmpty(st.getLastLoginTime())) {
					System.out.println(st.getLastLoginTime());
					if (st.getLastLoginTime() == "最后登录时间") {
						query.orderBy(criteriaBuilder.desc(root.get("LastLoginTime")));
					} else {
						query.orderBy(criteriaBuilder.desc(root.get("CreateTime")));
					}

				}

				return p;
			}

		};
	}

	// 根据id修改是否锁定
	@RequestMapping("/xglock")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public Map<String, Object> xglock(HttpServletRequest request) throws ParseException {
		String IsLockout = request.getParameter("isLockout");
		
		String Id = request.getParameter("id");

		Map<String, Object> map = new HashMap<String, Object>();

 if(IsLockout.equals("是")) {
		Integer i = userdao.orisLockout(IsLockout,Id);
		if (i > 0){
			map.put("msg", "1");
		} else {
			map.put("msg", "0");
		}
 }else {
	 Integer ii = userdao.orisLockouts(IsLockout,Id);
		if (ii > 0){
			map.put("msg", "1");
		} else {
			map.put("msg", "0");
		}
 }		
		
	
		return map;

	}

	// 重置密码
	@RequestMapping("/editpass")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public Map<String, Object> editpass(String Id) {

		Integer v = usersimpl.editpass(Id);

		Map<String, Object> map = new HashMap<String, Object>();
		if (v > 0) {
			map.put("msg", "1");
		} else {
			map.put("msg", "0");
		}
		return map;

	}

	// 添加
	@RequestMapping("/adduser")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public Map<String, Object> adduser(Users users) {
		String Id = UUIDutils.findkeyUtil();
		users.setId(Id);
		Date date = new Date();
		users.setCreateTime(date);
		users.setIsLockout("否");
		System.out.println(users);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			userdao.saveAndFlush(users);
			map.put("msg", "1");
			return map;
		} catch (Exception e) {
			// TODO: handle exception
			map.put("msg", "0");
			return map;
		}

	}

	// 修改
	@RequestMapping("/xgstulp")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public Map<String, Object> xgstulp(String LoginName, String ProtectEMail, String protectMTel, String Id) {

		Map<String, Object> mape = new HashMap<String, Object>();
		Integer h = userdao.xguserslpp(LoginName, ProtectEMail, protectMTel, Id);

		if (h > 0) {
			mape.put("code", "1");

		} else {

			mape.put("code", "0");
		}
		return mape;
	}

	// 删除
	@RequestMapping("/delstu")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public Map<String, Object> delstu(String Id) {

	
		Map<String, Object> mape = new HashMap<String, Object>();

		Integer s = userdao.deluserslpp(Id);
		if (s > 0) {
			mape.put("code", "1");
		} else {
			mape.put("code", "0");
		}

		return mape;
	}

	/*
	 * @RequestMapping("/getrolesid") public Roles getrolesid() throws
	 * UnsupportedEncodingException, JsonProcessingException { //生成id String
	 * cs=UUIDutils.findkeyUtil(); System.out.println(cs); String
	 * v=TokenUtil.unsign("32c8242b-ebc2-4c88-b367-65a0b46101e9");
	 * System.out.println(v); return null; }
	 */

	@RequestMapping("/getuserroles")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public List<Roles> getuserroles() {
		/* List<Userroles> list=userrolesdao.getuserroles(); */
		List<Roles> li = rolesdao.getroles();

		return li;
	}

	@RequestMapping("/getuserroless")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public List<Roles> getuserroless(String id) {

		List<Users> li = userdao.getalls(id);
		List<Roles> r = new ArrayList<Roles>();

		for (int i = 0; i < li.get(0).getRoles().size(); i++) {
			Roles rr = new Roles();
			rr.setId(li.get(0).getRoles().get(i).getId());
			rr.setName(li.get(0).getRoles().get(i).getName());
			r.add(rr);
		}
		return r;
	}

	// 穿梭框的添加
	@RequestMapping("/getuserrolessadd")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public List<com.soso.entity.Userroles> getuserrolessadd(String UserId, String RoleId) {

		Users u = userdao.getallss(UserId);
		Roles r = rolesdao.getallroles(RoleId);
		com.soso.entity.Userroles uu = new com.soso.entity.Userroles(88, u, r);
		userrolesdao.saveAndFlush(uu);

		return null;
	}

	@RequestMapping("/getuserrolessdel")
	@ResponseBody
	@CrossOrigin(origins = "*")
	public List<com.soso.entity.Userroles> getuserrolessdel(String UserId, String RoleId) {

		Users u = userdao.getallss(UserId);
		Roles r = rolesdao.getallroles(RoleId);
		com.soso.entity.Userroles uu = new com.soso.entity.Userroles(88, u, r);
		System.out.println(u);
		Integer v = userrolesdao.dels(UserId, RoleId);

		System.out.println(v);
		return null;
	}

}
